import { defineStore } from 'pinia'
import { h, reactive, ref, toRefs } from 'vue'
import { getCurrentUser, login } from '@/api/user'
import { TeamOutlined } from '@ant-design/icons-vue'
import { getProjectListApi } from '@/api/busi'

const useUserStore = defineStore(
  'user',
  () => {
    const token = ref('')
    const sessionHaskKey = ref('')
    const state = reactive({
      userInfo: {},
      permissions: [],
      menuList: []
    })

    function getUserInfo() {
      return new Promise((resolve, reject) => {
        getCurrentUser()
          .then(async (res) => {
            if (res) {
              state.userInfo = res
              resolve(res)
            } else {
              reject()
            }
          })
          .catch((e) => {
            reject(e)
          })
      })
    }
    function getProjectAll() {
      return new Promise((resolve, reject) => {
        getProjectListApi({ status: '正常' })
          .then(async (res) => {
            if (res) {
              state.menuList = res.items
              resolve(res)
            } else {
              reject()
            }
          })
          .catch((e) => {
            reject(e)
          })
      })
    }

    function doLogin(params) {
      return new Promise((resolve, reject) => {
        login(params)
          .then(async (res) => {
            token.value = res.AccessToken
            sessionHaskKey.value = res.SessionHaskKey
            // 每次登录成功,获取下字典信息(需要先调用获取用户信息,因为接口需要用户信息
            await getUserInfo()
            await getProjectAll()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    }

    function doLogout() {
      token.value = ''
      location.reload()
    }

    return {
      getProjectAll,
      getUserInfo,
      doLogin,
      doLogout,
      token,
      sessionHaskKey,
      ...toRefs(state)
    }
  },
  {
    persist: {
      storage: localStorage,
      paths: ['token', 'sessionHaskKey']
    }
  }
)

export default useUserStore
